package com.wcj.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wcj.springboot.controller.dto.UserDTO;
import com.wcj.springboot.entity.User;
import com.wcj.springboot.exception.ServiceException;
import com.wcj.springboot.mapper.UserMapper;
import com.wcj.springboot.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcj.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wcj
 * @since 2022-08-16
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public UserDTO login(UserDTO userDTO) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", userDTO.getUsername());
        query.eq("password", userDTO.getPassword());
        List<User> list = list(query);
        if (list.size() != 0) {
            BeanUtil.copyProperties(list.get(0), userDTO, true);
            userDTO.setToken(TokenUtils.getToken(list.get(0).getId().toString(),list.get(0).getPassword()));
            return userDTO;
        } else {
            throw new ServiceException("5000","用户名或密码错误");
        }
    }

    @Override
    public User register(UserDTO userDTO) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", userDTO.getUsername());
        query.eq("password", userDTO.getPassword());
        List<User> list = list(query);
        if (list.size() == 0) {
            User user = new User();
            BeanUtil.copyProperties(userDTO, user, true);
            save(user);
            return user;
        }else{
            throw new ServiceException("5000","用户名存在");
        }

    }


}
